package com.ruoyi.web.controller.teach;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.teach.domain.Teacher;
import com.ruoyi.teach.service.ITeacherService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 教师管理Controller
 *
 * @author ruoyi
 * @date 2023-11-22
 */
@RestController
@RequestMapping("/teach/teacher")
public class TeacherController extends BaseController
{
    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询教师管理列表
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:list')")
    @GetMapping("/list")
    public TableDataInfo list(Teacher teacher)
    {
        startPage();
        List<Teacher> list = teacherService.selectTeacherList(teacher);
        return getDataTable(list);
    }

    /**
     * 导出教师管理列表
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:export')")
    @Log(title = "教师管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Teacher teacher) throws ParseException, JsonProcessingException {
        List<Teacher> list = teacherService.selectTeacherList(teacher);
        ObjectMapper objectMapper = new ObjectMapper();;
        for (Teacher item : list) {
            JSONArray jsonArray = JSON.parseArray(item.getAwards());// new JSONArray(item.getAwards());
            // 获取第一个元素（JSONObject）
            JSONObject firstObject = jsonArray.getJSONObject(0);
            // 处理第一个元素
            if (firstObject.getString("award_name") != null) {
                item.setAwardName(firstObject.getString("award_name"));
            }
            if (firstObject.getString("award_department") != null) {
                item.setAwardDepartment(firstObject.getString("award_department"));
            }
            if (firstObject.getString("award_date") != null) {
                item.setAwardDate(new SimpleDateFormat("yyyy.MM").parse(firstObject.getString("award_date")));
            }
        }
        ExcelUtil<Teacher> util = new ExcelUtil<Teacher>(Teacher.class);
        util.hideColumn("awards"); // 隐藏授予情况总体
        util.exportExcel(response, list, "教师数据");
    }

    /**
     * 获取教师管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:query')")
    @GetMapping(value = "/{teacherId}")
    public AjaxResult getInfo(@PathVariable("teacherId") Long teacherId)
    {
        return success(teacherService.selectTeacherByTeacherId(teacherId));
    }

    /**
     * 新增教师管理
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:add')")
    @Log(title = "教师管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Teacher teacher)
    {
        return toAjax(teacherService.insertTeacher(teacher));
    }

    /**
     * 修改教师管理
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:edit')")
    @Log(title = "教师管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Teacher teacher)
    {
        return toAjax(teacherService.updateTeacher(teacher));
    }

    /**
     * 删除教师管理
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:remove')")
    @Log(title = "教师管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{teacherIds}")
    public AjaxResult remove(@PathVariable Long[] teacherIds)
    {
        return toAjax(teacherService.deleteTeacherByTeacherIds(teacherIds));
    }

    /**
     * 报名管理模版下载
     */
//    @GetMapping("/importTemplate")
//    public AjaxResult importTemplate() {
//        ExcelUtil<Teacher> util = new ExcelUtil<Teacher>(Teacher.class);
//        return util.importTemplateExcel("教师管理模板");
//    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Teacher> util = new ExcelUtil<Teacher>(Teacher.class);
        util.importTemplateExcel(response, "教师数据");
    }

    /**
     * 教师管理导入
     */
    @PreAuthorize("@ss.hasPermi('teach:teacher:import')")
    @Log(title = "教师管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<Teacher> util = new ExcelUtil<Teacher>(Teacher.class);
        System.out.println(file.getInputStream());
        // 日期字符串转为时间
        List<Teacher> teacherList = util.importExcel(file.getInputStream());
        for (Teacher teacher : teacherList) {
            JSONArray awards = new JSONArray();
            JSONObject firstObject = new JSONObject();
            firstObject.put("award_name", teacher.getAwardName());
            firstObject.put("award_department", teacher.getAwardDepartment());
            firstObject.put("award_date", teacher.getAwardDate());
            awards.add(firstObject);
            teacher.setAwards(awards.toJSONString());
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = teacherService.importTeacherList(teacherList, updateSupport, operName);
        return AjaxResult.success(message);
    }
}
